﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.OpenApi.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QiAdmin.Core.Models;
using QiAdmin.Core.Services.Cache;
using QiAdmin.Core.Services.Token;
using QiAdmin.Model.Dtos.Output;
using QiAdmin.Service.IService;

namespace QiAdmin.Core.Attributes
{
    public class PermissionAttribute : ActionFilterAttribute
    {

        readonly PermissionType[] _permission;

        public PermissionAttribute(params PermissionType[] permission)
        {
            _permission = permission;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            ITokenService tokenService = App.GetService<ITokenService>();
            ICacheService cacheService = App.GetService<ICacheService>();

            var tokenData = tokenService.ParseToken(context.HttpContext);
            var roleMenus = cacheService.Get<List<TSysRoleMenu_OUT>>(App.StaticData.CacheKey_RoleMenu);
            string tagName = ((ControllerActionDescriptor)context.ActionDescriptor).ControllerName;
            var userPermission = roleMenus.FindAll(s => s.RoleId == tokenData.UserRole && s.MenuApiTag == tagName);
            if (!userPermission.Exists(s => _permission.Any(p => p.GetDisplayName().Contains(s.MenuPermission.Replace(",", "")))))
            {
                context.HttpContext.Response.StatusCode = 403;
                //context.Result = new ApiJsonResult(ResultType.Error, "权限不足！");
            }

            base.OnActionExecuting(context);
        }
    }
}
